package com.calefk.modules.files 
{
	
	import flash.display.Loader;
	import flash.net.FileReference;
	import flash.events.Event;
	import flash.net.FileFilter;

	public class FileSelector 
	{
		public var file:FileReference;
		public var fileLoader: Loader;
		public var fileType: String;
		private var imageFileTypes: FileFilter;
		
		public static const TYPE_IMAGES :String = "images";
		
		public var fileSelected: Boolean = false;
		public var fileCanceled: Boolean = false;
		
		public function FileSelector(fileType:String) {
			this.fileType = fileType;
			switch (fileType) {
				case TYPE_IMAGES:
					imageFileTypes = new FileFilter("Images (*.jpg, *.png)", "*.jpg;*.png"); 
					break;
				default:
					imageFileTypes = new FileFilter("Images (*.jpg, *.png)", "*.jpg;*.png"); 
					break;
			}
			clearFile();
		}
		
		public function showDialog():void {
			file = new FileReference();
			file.browse([imageFileTypes]);
			file.addEventListener(Event.SELECT, selectFile);
			file.addEventListener(Event.CANCEL, cancelDialog);
		}
		
		private function cancelDialog(e:Event):void {
			fileCanceled = true;
		}
		
		private function selectFile(e:Event):void {
			file.addEventListener(Event.COMPLETE, loadFile);
			file.load();
		}
		 
		private function loadFile(e:Event):void {
			fileLoader = new Loader();
			fileLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
			fileLoader.loadBytes(file.data);
		}
		 
		private function loadComplete(e:Event):void {
			fileSelected = true;
		}
		
		public function clearFile(): void {
			this.file = null;
			if (this.fileLoader) {
				this.fileLoader.unload();
			}
			this.fileLoader = null;
			fileSelected = false;
			fileCanceled = false;
		}
		
		public function clean():void {
			clearFile();
			this.fileType = null;
			this.imageFileTypes = null;
		}
		
	}

}